/*
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-08-21 12:07:24
 * @LastEditTime: 2025-09-19 17:37:15
 */
import { ipcMain } from 'electron'
import AuthService from '../services/authService'
import { fail } from '../utils/response'
import NetworkService from '../services/networkService'
import UserProfileService from '../services/userProfileService'
import { WorkLogService } from '../services/workLog'
import DeskDomainService from '../services/deskDomainService'
import FoodDomainService from '../services/foodDomainService'
import DeviceDomainService from '../services/deviceDomainService'

// 注册IPC处理器
// // 保存/更新
// await window.api.invoke('auth', 'save', { username: '18888888888', password: '123' })

// // 读取单个
// const one = await window.api.invoke('auth', 'get', { username: '18888888888' })

// // 读取全部
// const all = await window.api.invoke('auth', 'get')

// // 删除
// await window.api.invoke('auth', 'remove', { username: '18888888888' })
export function registerDatabaseHandlers() {
    // 统一 user 域
    ipcMain.handle('rpc:users', async (event, { action, payload }: { action: string; payload?: any }) => {
        try {
            switch (action) {
                case 'save': {
                    const { username, password, userId } = payload || {}
                    return AuthService.saveCredential(username, password, userId)
                }
                case 'passport/login': {
                    const { username, password } = payload || {}
                    return AuthService.login(username, password)
                }
                default:
                    return fail(`Unknown action: ${action}`, 400)
            }
        } catch (error: any) {
            return fail(error.message)
        }
    })

    // 统一 net 域
    ipcMain.handle('rpc:net', async (event, { action, payload }: { action: string; payload?: any }) => {
        try {
            switch (action) {
                case 'isOnline':
                    return { status: 200, message: 'success', data: NetworkService.getOnline() }
                case 'probe':
                    return { status: 200, message: 'success', data: await NetworkService.isOnline() }
                case 'setOnline':
                    NetworkService.setOnline(!!payload?.online)
                    return { status: 200, message: 'success', data: NetworkService.getOnline() }
                default:
                    return fail(`Unknown action: ${action}`, 400)
            }
        } catch (error: any) {
            return fail(error.message)
        }
    })

    // 统一 userProfile 域
    ipcMain.handle('rpc:userProfile', async (event, { action, payload }: { action: string; payload?: any }) => {
        try {
            switch (action) {
                case 'save':
                    const { userId, profileData } = payload || {}
                    return UserProfileService.saveProfile(userId, profileData)
                case 'get':
                    const { userId: getStoreUserId } = payload || {}
                    return UserProfileService.getProfile(getStoreUserId)
                case 'getAll':
                    return UserProfileService.getAllProfiles()
                default:
                    return fail(`Unknown action: ${action}`, 400)
            }
        } catch (error: any) {
            return fail(error.message)
        }
    })
    // 旧的 auth:* 通道已移除，统一使用 rpc:auth

    // 统一 workLog 域
    ipcMain.handle('rpc:workLog', async (event, { action, payload }: { action: string; payload?: any }) => {
        try {
            switch (action) {
                case 'workStatus':
                    return WorkLogService.workStatus()
            }
        } catch (error: any) {
            return fail(error.message)
        }
    })

    // 统一 desk 域（桌台 + 桌台订单，仅保留批量新增）
    ipcMain.handle('rpc:desk', async (event, { action, payload }: { action: string; payload?: any }) => {
        try {
            switch (action) {
                case 'batchUpsert':
                    return DeskDomainService.deskBatchUpsert(payload?.desks || [])
                case 'order/batchUpsert':
                    return DeskDomainService.orderBatchUpsert(payload?.orders || [])
                case 'record/batchUpsert':
                    return DeskDomainService.recordBatchUpsert(payload?.records || [])
                case 'orderFood/batchUpsert':
                    return DeskDomainService.orderFoodBatchUpsert(payload?.orderFoods || [])
                case 'food/batchUpsert':
                    return FoodDomainService.foodBatchUpsert(payload?.foods || [])
                case 'foodBind/batchUpsert':
                    return FoodDomainService.foodBindBatchUpsert(payload?.binds || [])
                case 'foodSku/batchUpsert':
                    return FoodDomainService.foodSkuBatchUpsert(payload?.skus || [])
                case 'printer/batchUpsert':
                    return DeviceDomainService.printerBatchUpsert(payload?.printers || [])
                case 'computer/batchUpsert':
                    return DeviceDomainService.computerBatchUpsert(payload?.computers || [])
                case 'printerSetting/batchUpsert':
                    return DeviceDomainService.printerSettingBatchUpsert(payload?.printerSettings || [])
                default:
                    return fail(`Unknown action: ${action}`, 400)
            }
        } catch (error: any) {
            return fail(error.message)
        }
    })
}
